from django.db import models
import hashlib

# Create your models here.
class User(models.Model):
	id = models.AutoField(primary_key=True)
	name = models.CharField(max_length=20, unique=True)
	password = models.CharField(max_length=128) #hash of password
	STATUS_CHOICES = (
		(0, 'Offline'),
		(1, 'Online'),
	)
	latitude = models.FloatField();
	longitude = models.FloatField();
	status = models.IntegerField(choices=STATUS_CHOICES)
	#distance: how far to show this person on map
	
	def __unicode__(self):
		return self.name
	
	def clean(self):
		from django.core.exceptions import ValidationError
		if len(self.name) < 4:
			raise ValidationError('Username must be at least 4 characters')
		if self.latitude > 90.0 or self.latitude <-90.0:
			raise ValidationError('Latitude must be in the range [-90.0, 90.0]')
		if self.longitude > 180.0 or self.longitude < -180.0:
			raise ValidationError('Longitude must be in the range [-180.0, 180.0]')


#connection is one-way
class Connection(models.Model):
	source = models.ForeignKey(User, related_name='connection_source') #follower
	target = models.ForeignKey(User, related_name='connection_target') #followee (being followed by source)

	class Meta:
	        unique_together = ("source", "target")

	def __unicode__(self):
		return self.source.name+' -> '+self.target.name

	def clean(self):
		from django.core.exceptions import ValidationError
		if self.source == self.target:
			raise ValidationError('You can\'t follow yourself!')

class Request(models.Model):
	source = models.ForeignKey(User, related_name='request_source') #request originator
	target = models.ForeignKey(User, related_name='request_target')#request receiver
#	REQUEST_TYPES = (
#		('Connection'),
#		('EventInvite'
	requestType = models.CharField(max_length=30)#, choices='REQUEST_TYPES')
	
	def __unicode__(self):
		return self.requestType+": "+self.source.name+" -> "+self.target.name

class PHash(models.Model):
	salt = '68bc75054c6051ffab76'
	def encode(self, pw):
		return hashlib.sha512(pw + self.salt).hexdigest()

class Message(models.Model):
	source = models.ForeignKey(User, related_name='msg_source')
	target = models.ForeignKey(User, related_name='msg_target')
	timestamp = models.CharField(max_length=15)
	text = models.CharField(max_length=140)
	read = models.BooleanField()
	def __unicode__(self):
		return self.source.name+' -> '+self.target.name+' ('+str(self.timestamp)+'): '+self.text
	
class Block(models.Model):
	source = models.ForeignKey(User, related_name='block_source')                  
	target = models.ForeignKey(User, related_name='block_target')

